from rest_framework import serializers
from django.contrib.auth.models import Permission as DjangoPermission, Group as DjangoGroup
from .models import PermissionCategory, PermissionExtension, RoleExtension, UserRoleAssignment


class PermissionCategorySerializer(serializers.ModelSerializer):
    """权限分类序列化器"""
    
    class Meta:
        model = PermissionCategory
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class DjangoPermissionSerializer(serializers.ModelSerializer):
    """Django内建权限序列化器"""

    class Meta:
        model = DjangoPermission
        fields = '__all__'
        read_only_fields = ['id']


class PermissionExtensionSerializer(serializers.ModelSerializer):
    """权限扩展序列化器"""
    
    permission = DjangoPermissionSerializer(read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    
    class Meta:
        model = PermissionExtension
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class PermissionDetailSerializer(serializers.ModelSerializer):
    """权限详情序列化器"""
    
    permission = DjangoPermissionSerializer()
    category = PermissionCategorySerializer(read_only=True)
    
    class Meta:
        model = PermissionExtension
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class DjangoGroupSerializer(serializers.ModelSerializer):
    """Django内建组序列化器"""

    permissions_count = serializers.SerializerMethodField()

    class Meta:
        model = DjangoGroup
        fields = '__all__'
        read_only_fields = ['id']

    def get_permissions_count(self, obj):
        return obj.permissions.count()


class RoleExtensionSerializer(serializers.ModelSerializer):
    """角色扩展序列化器"""
    
    group = DjangoGroupSerializer(read_only=True)
    permissions_count = serializers.SerializerMethodField()
    users_count = serializers.SerializerMethodField()
    
    class Meta:
        model = RoleExtension
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_permissions_count(self, obj):
        return obj.group.permissions.count()
    
    def get_users_count(self, obj):
        # 统计UserRoleAssignment表中的活跃分配记录
        from .models import UserRoleAssignment
        return UserRoleAssignment.objects.filter(
            role=obj,
            status='active'
        ).count()


class RoleDetailSerializer(serializers.ModelSerializer):
    """角色详情序列化器"""
    
    group = DjangoGroupSerializer()
    permissions = serializers.SerializerMethodField()
    users = serializers.SerializerMethodField()
    
    class Meta:
        model = RoleExtension
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_permissions(self, obj):
        permissions = obj.get_permissions()
        return PermissionExtensionSerializer(
            [p.permissionextension for p in permissions if hasattr(p, 'permissionextension')],
            many=True
        ).data
    
    def get_users(self, obj):
        from apps.authentication.serializers import UserProfileSerializer
        users = obj.group.user_set.filter(is_active=True)
        return UserProfileSerializer(users, many=True).data


class UserRoleAssignmentSerializer(serializers.ModelSerializer):
    """用户角色分配序列化器"""
    
    user_username = serializers.CharField(source='user.username', read_only=True)
    user_email = serializers.CharField(source='user.email', read_only=True)
    role_name = serializers.CharField(source='role.name', read_only=True)
    assigned_by_username = serializers.CharField(source='assigned_by.username', read_only=True)
    is_active_status = serializers.SerializerMethodField()
    
    class Meta:
        model = UserRoleAssignment
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'assigned_at']
    
    def get_is_active_status(self, obj):
        return obj.is_active()


class UserPermissionSerializer(serializers.Serializer):
    """用户权限序列化器"""

    user_id = serializers.IntegerField()
    username = serializers.CharField()
    email = serializers.CharField()
    permissions = serializers.ListField(child=serializers.CharField())
    roles = serializers.ListField(child=serializers.CharField())

    # Serializer不需要Meta.fields，因为字段已经明确定义
